import {createReducer} from 'redux-act';
import u from 'updeep';
import {createAction2} from '../util';
import cache from '../util/cache';
import {bed, up, get, nullKey} from '../util/bed';
/*import cache from '../util/cache';*/
import * as ajax from '../util/ajax';
import * as http from '../util/http';
const name = 'writeReport';
const [
    load,
    create,
    modify,
    del
] = [
    `${name}_LOAD`,
    `${name}_CREATE`,
    `${name}_MODIFY`,
    `${name}_DEL`
].map(createAction2);

export const actions = {
    load: ({params: {type} = {}}, q = {}, forceLoad) => cache(
        `dict.${type}`
        , bed(
            ajax.get(http.makeUrl(`/${name}/${type}`, q)),
            load,
            {
                key: type
            }
        )
        , {forceLoad}
    ),
    create: (data, {type}) => bed(ajax.post(`/${name}/${type}`, data), create, {
        key: type,
        data
    }),
    modify: (data, {params: {type} = {}}) => bed(ajax.put(`/${name}/${type}`, data), modify, {
        key: type,
        data
    }),
    del: (data, {params: {type} = {}}) => bed(ajax.del(`/${name}/${type}/${data.Id}`), del, {
        key: type,
        data
    })
};

export default createReducer({
    [load]: get,
    [create]: (state, payload, {data, key}) => {
        let result = up(state, payload, nullKey);
        const {data: Id} = payload;
        if (Id) {
            data.Id = Id;
            result = u({[key]: (arr) => [].concat(arr, [data])}, result);
        }
        return result;
    },
    [modify]: (state, payload, {data, key, done}) => {
        let result = up(state, payload);
        if (done) {
            result = u({[key]: u.map(d => (d.Id === data.Id ? data : d))}, result);
        }
        return result;
    },
    [del]: (state, payload, {data, key, done}) => {
        let result = up(state, payload);
        if (done) {
            result = u({[key]: u.reject(d => d.Id === data.Id)}, result);
        }
        return result;
    }
}, {});
